import {
    request,
    AbstractBookCrawler,
    BasicBook,
    SearchBookResult,
    Book,
    BasicChapter,
    BookCrawlerTest,
    BookSource,
    getPathFromUrl,
    htmlToString,
} from "../../common/common_node.js";

class BookCrawler extends AbstractBookCrawler {


    async searchBook(keyword, pageNum) {

        let url = `${this.source.searchBaseUrl}/modules/article/search.php?q=${keyword}`;
        const $ = await (await request(url)).doc();
        const bookArr = [];
        const rows = $('#jieqi_page_contents .c_row');

        const keys = [];

        rows.each(function (i, e) {
            const bookNameA = $(e).find('.c_subject a');
            const name = bookNameA.text();
            const author = $(e).find(".c_tag .c_value").eq(0).text();
            const key = name + '-' + author;
            if (keys.includes(key)) {
                return;
            }
            keys.push(key);
            bookArr.push(new BasicBook({
                name: name,
                author: author,
                path: getPathFromUrl(bookNameA.attr('href')),
                catalogPath: getPathFromUrl($(e).find('div:eq(1) div:eq(0) a:eq(1)').attr('href')),
            }));
        });

        return new SearchBookResult({
            pageNum: 1, pages: 1, keyword: keyword, bookList: bookArr
        });
    }

    async bookDetails(path) {
        const $ = await (await request(this.source.bookBaseUrl + path)).doc();
        return new Book({
            name: $("meta[property='og:novel:book_name']").attr('content'),
            author: $("meta[property='og:novel:author']").attr('content'),
            path: path,
            catalogPath: getPathFromUrl($("meta[property='og:url']").attr('content')),
            intro: htmlToString($('.tabcontent .tabvalue').eq(0).text()),
            coverUrl: $("meta[property='og:image']").attr('content'),
            type: $("meta[property='og:novel:category']").attr('content'),
        });
    }

    async bookCatalog(path) {
        const $ = await (await request(this.source.bookBaseUrl + path)).doc();
        const chapters = $('ul.chapters ul.chapters li.chapter a');
        let catalog = [];
        chapters.each(function (i, elem) {
            const item = $(elem);
            catalog.push(new BasicChapter({
                index: i, title: item.text(), path: getPathFromUrl(item.attr("href"))
            }));
        });
        return catalog;
    }

    async chapterContent(path) {
        function removeEnding(str, ending) {
            if (str.endsWith(ending)) {
                return str.slice(0, -ending.length);
            }
            return str;
        }

        const $ = await (await request(this.source.bookBaseUrl + path)).doc();
        const contentHtml = removeEnding($("#clickeye_content").html().replace(/\(阅读库 www.yuedsk.com\)/gi, "").replace(/\(阅读库www.yuedsk.com\)/gi, ""), "阅读库 www.yuedsk.comyuedsk www.yuedsk.com");
        return htmlToString(contentHtml);
    }
}

const source = {
    "id": "free_book_js/13",
    "name": "阅读库",
    "portalUrl": "http://www.yuedsk.com",
    "searchBaseUrl": "http://www.yuedsk.com",
    "bookBaseUrl": "http://www.yuedsk.com",
    "active": true
};

await new BookCrawlerTest(new BookCrawler(BookSource.createTestBookSource(source)), {
    enableSearch: true, keyword: "重生",
}).run();

